package com.gx.smart.building.ui.knowledge

import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.FrameLayout
import com.blankj.utilcode.util.TimeUtils
import com.gx.smart.base.BaseMVVMActivityV3
import com.gx.smart.building.R
import com.gx.smart.building.databinding.ActivityKnowledgeArticleDetailBinding
import com.gx.smart.building.ui.knowledge.viewmodel.KnowledgeViewModel

class KnowledgeArticleDetailActivity : BaseMVVMActivityV3<KnowledgeViewModel>() {
    private lateinit var viewBinding: ActivityKnowledgeArticleDetailBinding
    private var mWebView: WebView? = null
    override fun onBindViewModel(): Class<KnowledgeViewModel> = KnowledgeViewModel::class.java

    override fun onBindLayout(): Int = R.layout.activity_knowledge_article_detail

    override fun getToolbarTitle(): String = "文章详情"

    override fun initContentView(root: ViewGroup?) {
        viewBinding = ActivityKnowledgeArticleDetailBinding.inflate(layoutInflater, root, true)
        mWebView = WebView(this)
        mWebView?.overScrollMode = View.OVER_SCROLL_NEVER
        mWebView?.isVerticalScrollBarEnabled = false
        viewBinding.container.addView(
            mWebView, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
            )
        )
    }

    override fun initData() {
        val id = intent.getStringExtra("id")
        viewModel.queryKnowledgeDetail(id!!).observe(this) {
            viewBinding.baseTitle.text = it.baseTitle
            val createTime = TimeUtils.millis2String(it.createTime, "yyyy-MM-dd")
            viewBinding.createTime.text = createTime
            viewBinding.viewNumber.text = it.viewNumber.toString()
            mWebView?.loadDataWithBaseURL(
                "about:blank",
                it.richTextContent,
                "text/html",
                "utf-8",
                ""
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // activity onDestroy时
        if (mWebView != null && mWebView?.parent != null) {
            (mWebView?.parent as ViewGroup).removeView(mWebView)
            mWebView?.destroy()
            mWebView = null
        }
    }
}